package won.user;

import won.db.DBConnect;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static java.lang.System.out;

public class UserManager {

    //没找到user 为空
    public static AbstractUser findUser(String username, String password){
        ResultSet resultSet;
        PreparedStatement prestmt;
        AbstractUser user = null;
        try {
            String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
            prestmt = DBConnect.getConnect().prepareStatement(sql);
            prestmt.setString(1, username);
            prestmt.setString(2, password);
            resultSet = prestmt.executeQuery();
            if (resultSet.next()) {
                String type = resultSet.getString("type");
                long id = resultSet.getLong("id");
                if ("teacher".equals(type)) {
                    user = new Teacher(); // 假设Teacher类有对应的构造器
                } else {
                    user = new Student(); // 同上
                }

                // 设置共有属性
                user.setId(id);
                user.setUsername(username);
                user.setPassword(password);
            }

            if (resultSet != null) {
                resultSet.close();
            }
            if (prestmt != null) {
                prestmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    public static void registerUser(String username, String password, String type){
        out.println("正在进行注册...");
        if (findUser(username, password) != null) {
            out.println("用户已存在，请直接登录！");
            new HomeDisplay();
        }
        PreparedStatement preparedStatement = null;
        String sql = null;
        boolean isSuccess = false;
        try {
            sql = "insert into user (username,password,type) values(?,?,?)";
            preparedStatement = DBConnect.getConnect().prepareStatement(sql);
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            preparedStatement.setString(3, type);
            int n = preparedStatement.executeUpdate();
            if (n == 1) {
                System.out.println("注册成功！");
            } else {
                System.out.println("注册失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        new HomeDisplay();
    }

    public static AbstractUser userLogin(String username, String password){
        AbstractUser user = findUser(username,password);
        return user;
    }
}
